/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xunome.game.multiplayerg;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.StringItem;
import xunome.xUnoME;
/**
*
* @author Sem iNick
*/
public class BluetoothConnectionClient implements DiscoveryListener, CommandListener {
private xUnoME mid;
private String name;
private Vector foundDevices; //Store found devices in inquirity
private Vector foundServices; // Store found xUno ME Servers
private Vector infoServers; // Store Server's and provider's name
private DiscoveryAgent agent;
private boolean stopAtFirst;
private Form serversForm;
private Command connect;
private Form out;
private ChoiceGroup serverOptions;
public BluetoothConnectionClient(xUnoME mid, Form outForm, String nome, boolean stop) {
this.mid = mid;
this.name = nome;
out = outForm;
stopAtFirst = stop;
serversForm = new Form("xUno ME - Bluetooth");
serversForm.append(new StringItem("Opening bluetooth.", ""));
mid.getLCD().setCurrent(serversForm);
}
public void startSearching() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, this);
serversForm.get(0).setLabel("Searching for devices.");
foundDevices = new Vector();
} catch (BluetoothStateException e) {
//#ifdef DEBUG
System.out.println("Error when open bluetooth.");
//#endif
Alert error = new Alert("ERROR:", "Bluetooth couldn't be initalized.",
null, AlertType.ERROR);
error.setTimeout(3000);
mid.getLCD().setCurrent(error);
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
int majorID = cod.getMajorDeviceClass();
if ((majorID == 0x0100) || (majorID == 0x0200)) {
foundDevices.addElement(btDevice);
}
//#ifdef DEBUG
else {
System.out.println("Major Device: " + majorID);
}
//#endif
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
try {
for (int s = 0; s < servRecord.length; s++) {
ServiceRecord service = servRecord[s];
foundServices.addElement(servRecord[s]);
if (stopAtFirst) {
agent.cancelServiceSearch(DiscoveryListener.SERVICE_SEARCH_TERMINATED);
break;
}
if (infoServers == null) {
infoServers = new Vector();
}
String serverName = (String) service.getAttributeValue(0x0100).getValue();
RemoteDevice provider = service.getHostDevice();
String providerName = "";
try {
providerName = provider.getFriendlyName(false);
} catch (IOException io) {
providerName = provider.getBluetoothAddress();
}
//#ifdef DEBUG
System.out.println(serverName);
//#endif
infoServers.addElement(serverName + '\0' + providerName);
//#ifdef DEBUG
System.out.println("Found server.");
//#endif
}
} catch (Exception e) {
//#ifdef DEBUG
System.out.println("Error when connecting with server.");
//#endif
}
}
public void serviceSearchCompleted(int transID, int respCode) {
//#ifdef DEBUG
System.out.println("Services Search Completed.");
//#endif
try {
synchronized (this) {
this.notifyAll();
}
} catch (Exception e) {
}
}
public void inquiryCompleted(int discType) {
if (foundDevices.size() > 0) {
serversForm.get(0).setLabel("Searching for servers.");
UUID[] id = {new UUID(BluetoothConnectionServer.UUID, false)};
int[] atri = {0x100, 0x102};
foundServices = new Vector();
for (int d = 0; (d < foundDevices.size())
&& (foundServices.size() == 0); d++) {
RemoteDevice dev = (RemoteDevice) foundDevices.elementAt(d);
//#ifdef DEBUG
try {
System.out.println("Found: " + dev.getFriendlyName(false));
} catch (Exception e){}
//#endif
try {
agent.searchServices(atri, id, dev, this);
synchronized (this) {
this.wait();
}
} catch (Exception e) {
//#if DEBUG
System.out.println("Error in services.");
System.out.println(e.getClass());
//#endif
}
}
if (foundServices.size() > 0) {
if (stopAtFirst) {
connectServer(0);
return;
}
connect = new Command("Connect", Command.OK, 1);
serverOptions = new ChoiceGroup("xUno ME Servers", ChoiceGroup.EXCLUSIVE);
serversForm.set(0, serverOptions);
serversForm.addCommand(connect);
serversForm.addCommand(new Command("Back", Command.BACK, 2));
serversForm.setCommandListener(this);
for (int s = 0; s < infoServers.size(); s++) {
String info = (String) infoServers.elementAt(s);
int delimiter = info.indexOf('\0');
String serverName = info.substring(0, delimiter);
String providerName = info.substring(delimiter + 1);
serverOptions.append(serverName + " (" + providerName + ")", null);
}
} else {
Alert notFound = new Alert("xUno ME", "No servers found.", null,
AlertType.WARNING);
notFound.setTimeout(3000);
mid.getLCD().setCurrent(notFound, out);
}
} else {
Alert noDevices = new Alert("xUno ME", "No devices found", null,
AlertType.WARNING);
noDevices.setTimeout(3000);
mid.getLCD().setCurrent(noDevices, out);
}
}
public void commandAction(Command c, Displayable d) {
if (c.equals(connect)) {
serversForm.removeCommand(connect);
int index = serverOptions.getSelectedIndex();
connectServer(index);
} else if (c.getCommandType() == Command.BACK) {
mid.getLCD().setCurrent(out);
}
}
private void connectServer(int index) {
final ServiceRecord service = (ServiceRecord) foundServices.elementAt(index);
new Thread() {
public void run() {
try {
StreamConnection con = (StreamConnection) Connector.open(service.
getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,
false));
new MultiPlayerManager(mid, name).getDataListener().
addConnetion(con);
} catch (IOException ex) {
Alert conError = new Alert("xUno ME", "Connection server error.", null,
AlertType.WARNING);
conError.setTimeout(3000);
mid.getLCD().setCurrent(conError, out);
}
}
}.start();
}
}